<?php

namespace Modules\Asset\Entities;

use Illuminate\Database\Eloquent\Builder;
use \Modules\Order\Entities\BaseOrder;

use ThrowException;
use Setting;

// 发货订单
class PackageOrder extends BaseOrder
{
    protected $guarded = [];
    protected $table = 'orders';

    static public $resourceName = '提货订单';
    static public $orderType = 'package';

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('packageOrder', function(Builder $builder) {
            $builder->type('package');
        });
    }

    public function package_skus()
    {
        return $this->hasMany('\Modules\Asset\Entities\PackageSku', 'pick_order_id');
    }

    // 计算邮费
    static public function calcCarriage($skuableMaps)
    {
        $carriage = 0;
        $carriageType = 1;  // 1为在线支付邮费  2为到付

        // 运费设置
        $carriageList = @Setting::get('sys_carriage')['package_sku'];

        if ($carriageList) {
            // 商品件数
            $noFreeCarriage = collect($skuableMaps)->sum('total');

            for ($i = count($carriageList) - 1;  $i>=0; $i --)
            {
                $total = @$carriageList[$i]['total'] ?: 0;
                if ($noFreeCarriage >= $total) {
                    $carriage = @$carriageList[$i]['carriage'] ?: 0;
                    break;
                }
            } 
        }

        return [
            $carriageType,
            $carriage
        ];
    }

    // 撤回物品仓库
    public function resetToPackage()
    {
        $this->closeAndRefund(2, '撤回物品仓库', [
            'refund_money' => $this->pay_money_price
        ]);
        foreach ($this->package_skus as $packageSku) {
            $packageSku->resetToPending();
        }
    }

    // 关闭事件
    public function closedListenerSync()
    {

    }

    // 创建后回调
    public function createdListenerSync()
    {
        // foreach ($this->skus as $orderSku) {
        //     $packageSku = $orderSku->base_sku;

        //     // 提交发货完成
        //     $packageSku->pick($this);
        // }
    }

    // 支付成功回调
    public function paidListenerSync()
    {
        // $this->ticket->pay_status = 1;
        // $this->ticket->save();

        // $this->autoFreight();
        // \Log::error('package order pay: ' . $this->id);

        $ids = @$this->options['package_sku_ids']  ?: [];

        // 取出此订单所有待处理的物品
        $list = $this->user->package_skus()->status('pending')->whereIn('id', $ids)->get();

        // 物品数不等于id数量，即有些物品已不在待发货状态
        // 此时不处理此订单
        if ($list->count() !== count($ids)) {
            \Log::error('发货订单异常，提货的物品不在待处理状态，订单id:' . $this->id . ' 用户id:' . $this->user_id);
            return false;
        }

        foreach ($list as $packageSku) {
            $packageSku->pick($this);
        }

        // 更改为可见
        $this->update([
            'is_visible' => 1
        ]);

        return true;

    }
}
